<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>商品管理系统</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.6.8/css/layui.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="layui-container" style="margin-top: 15px;">
        <div class="layui-card">
            <div class="layui-card-header">
                <!-- 添加搜索区域 -->
                <div class="layui-row">
                    <div class="layui-col-md4">
                        <div class="layui-form layui-form-item" style="margin-bottom: 0;">
                            <div class="layui-input-inline">
                                <input type="text" id="searchName" placeholder="请输入商品名称" class="layui-input">
                            </div>
                            <button class="layui-btn" onclick="searchProducts()">搜索</button>
                        </div>
                    </div>
                    <div class="layui-col-md8" style="text-align: right;">
                        <button class="layui-btn" onclick="openAddDialog()">添加商品</button>
                    </div>
                </div>
            </div>
            <div class="layui-card-body">
                <table id="productTable" lay-filter="productTable"></table>
            </div>
        </div>
    </div>

    <!-- 添加/编辑商品的表单 -->
    <div id="productForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="formTest">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-block">
                    <div class="layui-input-inline" style="width: 120px;">
                        <input type="text" name="price" required lay-verify="required|number" class="layui-input" id="price">
                    </div>
                    <div class="layui-input-inline" style="width: 100px;">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-xs" onclick="adjustPrice(1)"><i class="layui-icon">&#xe654;</i></button>
                            <button type="button" class="layui-btn layui-btn-xs" onclick="adjustPrice(-1)"><i class="layui-icon">&#xe67e;</i></button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">库存</label>
                <div class="layui-input-block">
                    <div class="layui-input-inline" style="width: 120px;">
                        <input type="text" name="stock" required lay-verify="required|number" class="layui-input" id="stock">
                    </div>
                    <div class="layui-input-inline" style="width: 100px;">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-xs" onclick="adjustStock(1)"><i class="layui-icon">&#xe654;</i></button>
                            <button type="button" class="layui-btn layui-btn-xs" onclick="adjustStock(-1)"><i class="layui-icon">&#xe67e;</i></button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <textarea name="description" class="layui-textarea"></textarea>
                </div>
            </div>
            <!-- 自定义字段区域 -->
            <div id="customFieldsContainer"></div>
            
            <!-- 添加自定义字段的行 -->
            <div class="layui-form-item">
                <label class="layui-form-label">自定义字段</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <input type="text" id="newFieldName" placeholder="字段名称" class="layui-input">
                </div>
                <div class="layui-input-inline" style="width: 100px;">
                    <select id="newFieldType" class="layui-input">
                        <option value="text">文本</option>
                        <option value="number">数字</option>
                        <option value="date">日期</option>
                    </select>
                </div>
                <div class="layui-input-inline" style="width: 80px;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="addCustomField()">
                        <i class="layui-icon">&#xe654;</i>添加
                    </button>
                </div>
            </div>
        </form>
    </div>

    <script src="https://www.layuicdn.com/layui-v2.6.8/layui.js"></script>
    <script>
        var table, layer, form;  // 声明全局变量
        // 固定步进值
        const STEP = 1;

        // 调整价格
        function adjustPrice(direction) {
            var price = parseFloat($('#price').val()) || 0;
            price += direction * STEP;
            if (price < 0) price = 0;
            $('#price').val(price.toFixed(2));
        }

        // 调整库存
        function adjustStock(direction) {
            var stock = parseInt($('#stock').val()) || 0;
            stock += direction * STEP;
            if (stock < 0) stock = 0;
            $('#stock').val(stock);
        }

        var customFields = [];
        
        // 加载自定义字段定义
        function loadCustomFields() {
            $.get('product/fields', function(fields) {
                customFields = fields;
                renderCustomFieldsForm();
                table.reload('productTable');
            });
        }

        // 添加自定义字段
        function addCustomField() {
            var name = $('#newFieldName').val();
            var type = $('#newFieldType').val();
            if (!name) {
                layer.msg('请输入字段名称');
                return;
            }
            if (customFields.some(field => field.name === name)) {
                layer.msg('字段名称已存在');
                return;
            }
            $.ajax({
                url: 'product/field/add',
                type: 'POST',
                data: {name: name, type: type},
                success: function() {
                    layer.msg('添加成功');
                    // 重新加载字段定义
                    $.get('product/fields', function(fields) {
                        // 保存当前表单的值
                        var currentFormData = form.val('formTest');
                        
                        customFields = fields;
                        // 重新渲染表单
                        renderCustomFieldsForm();
                        
                        // 恢复之前的值
                        form.val('formTest', currentFormData);
                        
                        // 清空输入框
                        $('#newFieldName').val('');
                        // 重置选择框
                        $('#newFieldType').val('text');
                        form.render('select');
                        // 重新初始化表格
                        initTable();
                    });
                },
                error: function(xhr, status, error) {
                    layer.msg('添加失败：' + error);
                    console.log('Add field error:', error);
                }
            });
        }

        // 删除自定义字段
        function removeCustomField(index) {
            var field = customFields[index];
            layer.confirm('确认删除字段 "' + field.name + '" 吗？', function(confirmIndex){
                $.ajax({
                    url: 'product/field/delete',
                    type: 'POST',
                    data: {name: field.name},
                    success: function() {
                        layer.msg('删除成功');
                        layer.close(confirmIndex);
                        // 重新加载字段定义
                        $.get('product/fields', function(fields) {
                            customFields = fields;
                            // 重新渲染表单和表格
                            renderCustomFieldsForm();
                            // 清空已删除字段的值
                            var formData = form.val('formTest');
                            delete formData['custom_' + field.name];
                            form.val('formTest', formData);
                            // 重新初始化表格
                            initTable();
                        });
                    },
                    error: function(xhr, status, error) {
                        layer.msg('删除失败：' + error);
                        console.log('Delete field error:', error);
                    }
                });
            });
        }

        // 渲染自定义字段表单
        function renderCustomFieldsForm() {
            var html = '';
            customFields.forEach(function(field, index) {
                html += `
                    <div class="layui-form-item">
                        <label class="layui-form-label">${field.name}</label>
                        <div class="layui-input-inline" style="width: 180px;">
                            <input type="${field.type === 'number' ? 'number' : 'text'}" 
                                   name="custom_${field.name}" 
                                   class="layui-input"
                                   value="${field.value || ''}"
                                   ${field.type === 'date' ? 'lay-verify="date"' : ''}>
                        </div>
                        <div class="layui-input-inline" style="width: 80px;">
                            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" 
                                    onclick="removeCustomField(${index})">
                                <i class="layui-icon">&#xe640;</i>删除
                            </button>
                        </div>
                    </div>
                `;
            });
            $('#customFieldsContainer').html(html);
            customFields.forEach(function(field) {
                if (field.type === 'date') {
                    layui.laydate.render({
                        elem: `input[name="custom_${field.name}"]`
                    });
                }
            });
            form.render();  // 重新渲染所有表单元素
        }

        layui.use(['table', 'layer', 'form'], function(){
            table = layui.table;
            layer = layui.layer;
            form = layui.form;
            
            // 初始化表格
            function initTable() {
                // 先获取自定义字段定义
                $.get('product/fields', function(fields) {
                    customFields = fields;
                    renderCustomFieldsForm();  // 渲染自定义字段表单
                    // 然后初始化表格
                    table.render({
                        elem: '#productTable'
                        ,url: 'product/list'
                        ,where: {}
                        ,cols: [[
                            {field: '_id', title: 'ID', hide: true}
                            ,{field: 'name', title: '商品名称'}
                            ,{field: 'price', title: '价格'}
                            ,{field: 'stock', title: '库存'}
                            ,{field: 'description', title: '描述'}
                            // 动态添加自定义字段列
                            ,...customFields.map(function(field) {
                                return {
                                    field: 'customFields.' + field.name,
                                    title: field.name,
                                    width: 120,
                                    templet: function(d) {
                                        return d.customFields ? d.customFields[field.name] || '' : '';
                                    }
                                };
                            })
                            ,{fixed: 'right', title:'操作', toolbar: '#tableBar', width:150}
                        ]]
                        ,page: true
                        ,parseData: function(res){
                            return {
                                "code": 0,
                                "msg": "",
                                "count": res.length,
                                "data": res
                            };
                        }
                    });
                }).fail(function(xhr, status, error) {
                    console.log('Load fields error:', error);
                    layer.msg('加载自定义字段失败');
                });
            }

            // 监听工具条
            table.on('tool(productTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'del'){
                    layer.confirm('确认删除吗？', function(index){
                        $.ajax({
                            url: 'product/delete',
                            type: 'POST',
                            data: {id: data._id},
                            success: function(res){
                                layer.close(index);
                                window.location.reload();
                            },
                            error: function(xhr, status, error) {
                                layer.close(index);
                                window.location.reload();
                            }
                        });
                    });
                } else if(obj.event === 'edit'){
                    openEditDialog(data);
                }
            });
            
            // 初始化表格
            initTable();
        });

        function openAddDialog() {
            layer.open({
                type: 1,
                title: '添加商品',
                content: $('#productForm'),
                area: ['600px', '90%'],
                maxHeight: window.innerHeight - 100,
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var formData = form.val('formTest');
                    // 清除可能存在的id字段
                    delete formData.id;
                    // 处理自定义字段
                    var customFieldsData = {};
                    customFields.forEach(function(field) {
                        var value = formData['custom_' + field.name];
                        if (field.type === 'number') {
                            value = parseFloat(value);
                        }
                        customFieldsData[field.name] = value;
                        delete formData['custom_' + field.name];
                    });
                    formData.customFields = JSON.stringify(customFieldsData);
                    $.ajax({
                        url: 'product/add',
                        type: 'POST',
                        data: formData,
                        success: function(){
                            layer.close(index);
                            window.location.reload();
                            // 清空表单
                            form.val('formTest', {
                                name: '',
                                price: '',
                                stock: '',
                                description: ''
                            });
                        },
                        error: function(xhr, status, error) {
                            layer.msg('添加失败：' + error);
                            window.location.reload();
                        }
                    });
                }
            });
        }

        function openEditDialog(data) {
            // 将 _id 赋值给隐藏的 id 字段
            var formData = {
                id: data._id,
                name: data.name,
                price: data.price,
                stock: data.stock,
                description: data.description
            };
            // 加载已有的自定义字段
            customFields = [];
            if (data.customFields) {
                Object.keys(data.customFields).forEach(function(key) {
                    customFields.push({
                        name: key,
                        type: typeof data.customFields[key] === 'number' ? 'number' : 'text',
                        value: data.customFields[key]
                    });
                });
                renderCustomFieldsForm();
                // 设置自定义字段的值
                customFields.forEach(function(field) {
                    formData['custom_' + field.name] = field.value;
                });
            }
            form.val('formTest', formData);
            layer.open({
                type: 1,
                title: '编辑商品',
                content: $('#productForm'),
                area: ['600px', '90%'],
                maxHeight: window.innerHeight - 100,
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var formData = form.val('formTest');
                    // 处理自定义字段
                    var customFieldsData = {};
                    customFields.forEach(function(field) {
                        var value = formData['custom_' + field.name];
                        if (field.type === 'number') {
                            value = parseFloat(value);
                        }
                        customFieldsData[field.name] = value;
                        delete formData['custom_' + field.name];
                    });
                    formData.customFields = JSON.stringify(customFieldsData);
                    $.ajax({
                        url: 'product/update',
                        type: 'POST',
                        data: formData,
                        success: function(){
                            layer.close(index);
                            window.location.reload();
                        },
                        error: function(xhr, status, error) {
                            layer.msg('更新失败：' + error);
                            window.location.reload();
                        }
                    });
                }
            });
        }

        // 添加搜索函数
        function searchProducts() {
            var searchName = $('#searchName').val();
            table.reload('productTable', {
                where: {
                    name: searchName
                },
                page: {
                    curr: 1 // 重新从第一页开始
                }
            });
        }
        
        // 添加回车键搜索功能
        $(document).ready(function(){
            $('#searchName').keypress(function(e){
                if(e.which == 13){ // 回车键的键值为13
                    searchProducts();
                }
            });
        });
    </script>

    <script type="text/html" id="tableBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
</body>
</html> 